<template>
  <div v-if="isExternal" :style="[styleExternalIcon, sizeStyle]" class="svg-external-icon svg-icon" v-on="$attrs" />
  <svg v-else class="svg-icon" aria-hidden="true" v-on="$attrs" :style="sizeStyle">
    <use :xlink:href="iconName" />
  </svg>
</template>
  
<script setup>
import { computed } from 'vue'
  
const props = defineProps({
  iconClass: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  },
  color: {
    type: String,
    default: ''
  },
  size: {
    type: [Number, String],
    default: ''
  }
})
  
const isExternal = computed(() => {
  return /^(https?:|mailto:|tel:)/.test(props.iconClass)
})
  
const iconName = computed(() => {
  return `#icon-${props.iconClass}`
})
  
const svgClass = computed(() => {
  if (props.className) {
    return 'svg-icon ' + props.className
  } else {
    return 'svg-icon'
  }
})

const sizeStyle = computed(() => {
  if (!props.size) return {}

  let size = props.size
  // 如果是数字，默认单位为 px
  if (typeof size === 'number' || !isNaN(Number(size))) {
    size = `${size}px`
  }
  
  return {
    width: size,
    height: size
  }
})
  
const styleExternalIcon = computed(() => {
  return {
    mask: `url(${props.iconClass}) no-repeat 50% 50%`,
    '-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`,
    'background-color': props.color || 'currentColor'
  }
})
</script>
  
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
  
.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>